package vip.indo.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * @Author: tianlianyin
 * @Date: 2024/11/27 15:08
 * @Descripition:
 */
@Configuration //标识为配置类
public class JacksonConfig {
    @Bean //标识为bean
    @Primary //标识为默认
    @ConditionalOnMissingBean(ObjectMapper.class)//当容器中没有ObjectMapper时，才创建这个bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();//创建xmlMapper
        objectMapper.getSerializerProvider() //获取序列化器提供者
                .setNullValueSerializer(new JsonSerializer<Object>() { //设置为空字符串
                    @Override
                    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                        jsonGenerator.writeString(""); // 设置为空字符串
                    }
                });
        return objectMapper;
    }
}
